package com.xxl.rpc.sample.client.controller;

import com.xxl.rpc.core.remoting.invoker.route.LoadBalance;
import com.xxl.rpc.sample.api.DemoService;
import com.xxl.rpc.sample.api.SunKunService;
import com.xxl.rpc.sample.api.dto.CVO;
import com.xxl.rpc.sample.api.dto.UserDTO;
import com.xxl.rpc.core.remoting.invoker.annotation.XxlRpcReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Controller;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class IndexController {

	@XxlRpcReference
	private DemoService demoService;

	@XxlRpcReference(loadBalance=LoadBalance.LRU)
	private SunKunService sunKunService;

	@RequestMapping("")
	@ResponseBody
	public UserDTO http(String name) {

		try {
			return demoService.sayHi(name);
		} catch (Exception e) {
			e.printStackTrace();
			return new UserDTO(null, e.getMessage());
		}
	}

	@RequestMapping("test")
	@ResponseBody
	public CVO test() {

		try {
			return demoService.hessian(new CVO());
		} catch (Exception e) {
			e.printStackTrace();

		}
		return null;
	}

	@RequestMapping("test2")
	@ResponseBody
	public String test2(String name) {
		return sunKunService.sayHi(name);
	}
	private static Logger logger = LoggerFactory.getLogger(IndexController.class);
	@Autowired
	private KafkaTemplate kafkaTemplate;

	@RequestMapping("kafka")
	@ResponseBody
	public String kafka(String topic,String value) {
		logger.error("日志测试error=========");
		logger.info("日志测试info=========");
		ListenableFuture<SendResult<String, Object>> listenableFuture= kafkaTemplate.send(topic,value);
		listenableFuture.addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
			@Override
			public void onFailure(Throwable throwable) {
				System.out.println("消息发送失败"+throwable.getStackTrace());
				System.out.println("消息发送失败2"+throwable.getMessage());
			}

			@Override
			public void onSuccess(SendResult<String, Object> stringObjectSendResult) {
				System.out.println("消息发送成功");
			}
		});
		return "success topic ="+topic+"value=="+value;
	}
	@RequestMapping("log")
	@ResponseBody
	public void log(String topic,String value) {
		logger.error("日志测试error========="+topic);
		logger.info("日志测试info========="+value);
	}

}
